package com.cloudlead.common.worker.client;

import com.cloudlead.common.lang.api.ActionRequest;
import com.cloudlead.common.lang.api.SimpleActionResponse;
import com.cloudlead.common.lang.serialize.BeanSerializeException;
import com.cloudlead.common.lang.serialize.JSON;
import com.cloudlead.common.worker.client.exception.RestClientException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.type.TypeFactory;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * 通用的API调用客户端
 *
 * @author 陆林(lulin@cloudlead-partners.com)
 * @version 2.0
 * @Description
 * @date 2014年11月12日 上午11:39:52
 * @since 2.0
 */
public class ApiClient {

    private static final String BASE_API_PATH = "/resources/request/";
    private final RestClientExecutor executor;

    public ApiClient(final String host, final int port) {
        try {
            executor = new RestClientExecutor(new URL("http", host, port, "/"));
        } catch (MalformedURLException e) {
            e.printStackTrace();
            throw new RestClientException("Create api client error", e);
        }
    }

    /**
     * 执行请求
     *
     * @param action
     * @param request
     * @return
     * @throws RestClientException
     * @Title: executeRequest
     */
    public <T> SimpleActionResponse<T> executeRequest(String action,
                                                      ActionRequest request, Class<T> responseClass) throws RestClientException {
        String json;
        try {
            json = JSON.toString(request);
        } catch (BeanSerializeException e) {
            e.printStackTrace();
            throw new RestClientException("json serialize error.", e);
        }

        String responseString = executor.post(BASE_API_PATH + action, json);
        try {
            SimpleActionResponse<T> response = JSON.toBean(responseString, SimpleActionResponse.class, responseClass);
            return response;
        } catch (BeanSerializeException e) {
            e.printStackTrace();
            throw new RestClientException("json deserialize error.", e);
        }

    }

}
